package com.mycat.service.auth.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mycat.dao.entity.auth.Admin;
import com.mycat.dao.entity.auth.RefAdminRole;
import com.mycat.dao.mapper.auth.AdminMapper;
import com.mycat.dao.mapper.auth.RefAdminRoleMapper;
import com.mycat.service.auth.AdminService;
import com.mycat.service.constant.auth.AdminState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 管理员信息Service
 *
 * @author Roger
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RefAdminRoleMapper refAdminRoleMapper;

    @Override
    public void addAdmin(Admin admin) {
        if (null != admin) {
            admin.setCreateDate(new Date());
            admin.setState(AdminState.unActivity.getCode());
            admin.setLoginCount(0);
        }
        adminMapper.insertSelective(admin);
    }

    @Override
    public void delAdmin(Integer[] ids) {
        for (Integer id : ids) {
            adminMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void updateAdmin(Admin admin) {
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    @Override
    public Admin findAdmin(Admin admin) {
        return adminMapper.selectAdmin(admin);
    }

    @Override
    public Admin findAdminRole(Admin param) {
        return adminMapper.selectAdminRole(param);
    }

    @Override
    public PageInfo<Admin> findAdmins(Page<Admin> page) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<Admin> admins = adminMapper.selectAll();
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        return pageInfo;
    }

    @Override
    public void addAdminRole(Integer[] roleIds, Integer adminId) {
        refAdminRoleMapper.deleteAdminRole(adminId);
        List<RefAdminRole> list = new ArrayList<>();
        RefAdminRole adminRole = null;
        for (Integer roleId : roleIds) {
            adminRole = new RefAdminRole();
            adminRole.setAdminId(adminId);
            adminRole.setRoleId(roleId);
            list.add(adminRole);
        }
        if(list.size() > 0){
            refAdminRoleMapper.insertList(list);
        }
    }
}
